package com.emapp.lccode.http

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.io.ByteArrayOutputStream
import java.lang.reflect.Type

/**
 *@Description: TODO
 *@Author:  zhang
 *@Date:   2023/6/29
 */

class BitmapConverterFactory : Converter.Factory() {

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *>? {
        if (type == Bitmap::class.java) {
            return Converter<ResponseBody, Bitmap> { value ->
                BitmapFactory.decodeStream(value.byteStream())
            }
        }
        return null
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<Annotation>,
        methodAnnotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<*, okhttp3.RequestBody>? {
        if (type == Bitmap::class.java) {
            return Converter<Bitmap, okhttp3.RequestBody> { value ->
                val byteStream = ByteArrayOutputStream()
                value.compress(Bitmap.CompressFormat.PNG, 100, byteStream)
                RequestBody.create("image/png".toMediaType(), byteStream.toByteArray())
            }
        }
        return null
    }
}